package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @ClassName ApUnlikesBehaviorServiceImpl
 * @Description TODO
 * @Author AWei
 * @DATE 2021/4/22 23:23
 * @Version 1.0
 */
@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements ApUnlikesBehaviorService {

    @Resource
    private ApBehaviorEntryService apBehaviorEntryService;

    /**
     * @param dto 不喜欢行为对象
     * @return 保存结果
     * @Description 保存不喜欢行为
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (ObjectUtils.isEmpty(apBehaviorEntry)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUnlikesBehavior apUnlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
        // 保存不喜欢
        if (ObjectUtils.isEmpty(apUnlikesBehavior) && dto.getType().equals(ApUnlikesBehavior.Type.UNLIKE.getCode())) {
            apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setType(dto.getType());
            apUnlikesBehavior.setCreatedTime(new Date());
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            save(apUnlikesBehavior);
        } else {//4.取消不喜欢
            apUnlikesBehavior.setType(dto.getType());
            updateById(apUnlikesBehavior);
        }
        return ResponseResult.okResult();
    }
}
